package com.example.demo.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Random;

public class VerficodeUtil {
    private BufferedImage image;
    private String ans="";

    public BufferedImage getImage(){
        int width=80;
        int height=25;
        BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //得到画笔
        Graphics2D graphics=(Graphics2D) image.getGraphics();
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.black);
        Random random=new SecureRandom();
        char[] arrays="QWERTYUPASDFGHJKLZXCVBNMqwertyupasdfghjkzxcvbnm".toCharArray();
        for(int i=0;i<4;i++) {
            ans+=arrays[random.nextInt(arrays.length)];
        }
        this.ans=ans;
        for(int j=0;j<5;j++) {
            int x1=random.nextInt(width/4);
            int y1=random.nextInt(height);
            int x2=random.nextInt(width/4);
            int y2=random.nextInt(height);
            graphics.drawLine(x1, y1, x2, y2);
        }
        graphics.setFont(new Font("TImes New Roman",Font.BOLD,20));
        graphics.drawString(ans, width/5, height*4/5);
        this.image=image;
        return image;
    }

    public String getText(){
        return ans;
    }

    public static void output(BufferedImage image, OutputStream out) throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}
